function cmd(cmd) {
  var h = null;

  h = new XMLHttpRequest();
  h.open('GET', '/smpprouter/cmd.php?c=' + cmd, false);
  h.send(null);
  
  return h.responseText;
}

function startProcess() {
  if(confirm("Do you want START process?")) {
    cmd('start');
  }
}

function stopProcess() {
  if(confirm("Do you want STOP process?")) {
    cmd('stop');
  }  
}

function restartProcess() {
  if(confirm("Do you want RESTART process?")) {
    cmd('restart');
  }
}

function reloadConfig() {
  if(confirm("Do you want RELOAD CONFIG?")) {
    cmd('reconfig');
  }  
}

function clearLog() {
  if(confirm("Do you want CLEAR LOG process?")) {
    cmd('clearlog');
  }  
}

function refreshLog(time) {
  document.getElementById('log_content').innerHTML = cmd('log');
  
  setTimeout(function() { refreshLog(time); }, time);
}

function refreshSessions(time) {
  document.getElementById('sess_content').innerHTML = cmd('sessions');
  
  setTimeout(function() { refreshSessions(time); }, time);
}

function refreshLogSize(time) {
  document.getElementById('log_size').innerHTML = cmd('logsize');
  
  setTimeout(function() { refreshLogSize(time); }, time);
}

function refreshProcessStatistics(time) {
  var ps = JSON.parse(cmd('ps'));

  var ps_pid = document.getElementById('ps_pid');
  var ps_cpu = document.getElementById('ps_cpu');
  var ps_mem = document.getElementById('ps_mem');
  var ps_vmem = document.getElementById('ps_vmem');
  var ps_pmem = document.getElementById('ps_pmem');
  var ps_time = document.getElementById('ps_time');
  var ps_cmd = document.getElementById('ps_cmd');

  if(ps['command']) {
    ps_pid.innerHTML = ps['pid'];
    ps_cpu.innerHTML = ps['cpu_percent'];
    ps_mem.innerHTML = ps['mem_percent'];
    ps_vmem.innerHTML = ps['mem_virtual'];
    ps_pmem.innerHTML = ps['mem_page'];
    ps_time.innerHTML = ps['start_time'];
    ps_cmd.innerHTML = ps['command'];
  } else {
    var empty = '---';
    ps_pid.innerHTML = empty;
    ps_cpu.innerHTML = empty;
    ps_mem.innerHTML = empty;
    ps_vmem.innerHTML = empty;
    ps_pmem.innerHTML = empty;
    ps_time.innerHTML = empty;
    ps_cmd.innerHTML = empty;
  }
  
  setTimeout(function() { refreshProcessStatistics(time); }, time);
}

var init = function() {
  refreshProcessStatistics(5000);
  refreshLogSize(1000);
  refreshSessions(1000);
  refreshLog(3000);
};

window.onload = init;
